//Copyright 2006, 2007 The Apache Software Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package org.apache.tapestry5.internal.portlet.services;

import static org.apache.tapestry5.ioc.internal.util.CollectionFactory.newList;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.List;

import javax.portlet.ActionResponse;
import javax.portlet.MimeResponse;
import javax.portlet.PortletRequest;
import javax.portlet.RenderResponse;

import org.apache.tapestry5.ComponentEventCallback;
import org.apache.tapestry5.ContentType;
import org.apache.tapestry5.EventConstants;
import org.apache.tapestry5.MarkupWriter;
import org.apache.tapestry5.dom.Attribute;
import org.apache.tapestry5.dom.Document;
import org.apache.tapestry5.dom.Element;
import org.apache.tapestry5.dom.Node;
import org.apache.tapestry5.internal.services.PageContentTypeAnalyzer;
import org.apache.tapestry5.internal.services.PageMarkupRenderer;
import org.apache.tapestry5.internal.services.PageResponseRenderer;
import org.apache.tapestry5.internal.structure.ComponentPageElement;
import org.apache.tapestry5.internal.structure.Page;
import org.apache.tapestry5.ioc.internal.util.InternalUtils;
import org.apache.tapestry5.portlet.PortletConstants;
import org.apache.tapestry5.portlet.services.PortletInterfaceProvider;
import org.apache.tapestry5.services.ContextPathEncoder;
import org.apache.tapestry5.services.ContextValueEncoder;
import org.apache.tapestry5.services.MarkupWriterFactory;
import org.apache.tapestry5.services.Response;
import org.slf4j.Logger;

public class PortletPageResponseRendererImpl implements PageResponseRenderer {

    private final Logger                  log = org.slf4j.LoggerFactory
                                                  .getLogger(PortletPageResponseRendererImpl.class);

    private final PortletRequest          _portletRequest;

    private final RenderResponse          _renderResponse;

    private final ActionResponse          _actionResponse;

    private final PageMarkupRenderer      _markupRenderer;

    private final MarkupWriterFactory     _markupWriterFactory;

    private final PageContentTypeAnalyzer _pageContentTypeAnalyzer;

    private final Response                _response;

    private final ContextValueEncoder     _contextValueEncoder;

    private final ContextPathEncoder      _contextPathEncoder;

    public PortletPageResponseRendererImpl(@PortletInterfaceProvider PortletRequest portletRequest,
                                           RenderResponse renderResponse, ActionResponse actionResponse,
                                           MarkupWriterFactory markupWriterFactory, PageMarkupRenderer markupRenderer,
                                           PageContentTypeAnalyzer pageContentTypeAnalyzer, Response response,
                                           ContextValueEncoder contextValueEncoder,
                                           ContextPathEncoder contextPathEncoder) {
        this._portletRequest = portletRequest;
        this._renderResponse = renderResponse;
        this._actionResponse = actionResponse;
        this._markupWriterFactory = markupWriterFactory;
        this._markupRenderer = markupRenderer;
        this._pageContentTypeAnalyzer = pageContentTypeAnalyzer;
        this._response = response;
        this._contextValueEncoder = contextValueEncoder;
        this._contextPathEncoder = contextPathEncoder;
    }

    @Override
    public void renderPageResponse(Page page) throws IOException {
        assert page != null;

        Object lifecyclePhase = this._portletRequest.getAttribute(PortletRequest.LIFECYCLE_PHASE);

        if (PortletRequest.ACTION_PHASE.equals(lifecyclePhase)) {
            this.handleActionRequest(page);
            return;
        }

        // For the moment, the content type is all that's used determine the model for the markup writer.
        // It's something of a can of worms.
        ContentType contentType = this._pageContentTypeAnalyzer.findContentType(page);

        PrintWriter pw = this._response.getPrintWriter(contentType.toString());

        MarkupWriter writer = this._markupWriterFactory.newMarkupWriter(contentType);

        this._markupRenderer.renderPageMarkup(page, writer);

        if (PortletRequest.RENDER_PHASE.equals(lifecyclePhase)) {
            this.handleRenderPhase(writer, pw);
            return;
        }

        // resource request or an unknown lifecycle phase
        // ...anyway output the complete markup
        writer.toMarkup(pw);
    }

    private void handleRenderPhase(MarkupWriter markupWriter, PrintWriter pw) {
        // extract the body from the DOM and use it as portlet body 
        Document document = markupWriter.getDocument();

        Element body = document.find("html/body");

        String childMarkup = body.getChildMarkup();

        pw.write(childMarkup);
        pw.flush();

        /** we need to extract the head-tag from the DOM and call
         *  PortletResponse.addProperty(MimeResponse.MARKUP_HEAD_ELEMENT, head-child-element)
         *  for each element within the head-tag, so the portlet container can add these tags to the actual head-tag.
         */
        Element head = document.find("html/head");

        for (Node child : head.getChildren()) {

            if (child instanceof Element) {

                Element element = (Element) child;

                this.addElementToHead(element);
            }
        }
    }

    private void handleActionRequest(Page page) {

        // TODO: implement as ActionRenderResponseGenerator

        if (this._actionResponse != null) {
            this._actionResponse.setRenderParameter(PortletConstants.PORTLET_MODE, this._portletRequest
                .getPortletMode().toString());
            this._actionResponse.setRenderParameter(PortletConstants.WINDOW_STATE, this._portletRequest
                .getWindowState().toString());

            final List context = newList();
            ComponentEventCallback callback = new ComponentEventCallback() {

                @Override
                @SuppressWarnings("unchecked")
                public boolean handleResult(Object result) {
                    if (result instanceof Collection) {
                        context.addAll((Collection) result);
                    }
                    else if (result instanceof Object[]) {
                        for (Object o : (Object[]) result) {
                            context.add(o);
                        }
                    }
                    else {
                        context.add(result);
                    }
                    return true;
                }
            };

            ComponentPageElement rootElement = page.getRootElement();

            rootElement.triggerEvent(EventConstants.PASSIVATE, null, callback);

            String[] contextArray = this.toContextStrings(context.toArray());
            System.out.println("PortletPageResponseRendererImpl.renderPageResponse() context = " + context);

            String contextPath = this._contextPathEncoder.encodeIntoPath(contextArray);

            String pageAndContext = "/" + page.getName() + "/" + contextPath;

            this._actionResponse.setRenderParameter(PortletConstants.PORTLET_PAGE, pageAndContext);
            System.out.println("PortletPageResponseRendererImpl.renderPageResponse() pageAndContext = "
                + pageAndContext);

            //String[] activationContext = collectActivationContextForPage(page);
        }
    }

    private void addElementToHead(Element element) {

        String tagName = element.getName();

        org.w3c.dom.Element headElement = this._renderResponse.createElement(tagName);

        String textContent = element.getChildMarkup();
        if (InternalUtils.isNonBlank(textContent)) {
            headElement.setTextContent(textContent);
        }

        for (Attribute attribute : element.getAttributes()) {
            String name = attribute.getName();
            String value = attribute.getValue();
            headElement.setAttribute(name, value);
        }

        this._renderResponse.addProperty(MimeResponse.MARKUP_HEAD_ELEMENT, headElement);
    }

    private String[] toContextStrings(Object[] context) {
        if (context == null) {
            return new String[0];
        }

        String[] result = new String[context.length];

        for (int i = 0; i < context.length; i++) {

            Object value = context[i];

            String encoded = value == null ? null : this._contextValueEncoder.toClient(value);

            if (InternalUtils.isBlank(encoded)) {
                throw new RuntimeException(PortletServicesMessages.contextValueMayNotBeNull());
            }

            result[i] = encoded;
        }

        return result;
    }
}
